package demo19_Lock;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * @author kunkun
 * @className Test06_DeadLock
 * @Description 测试死锁
 * @date 2025/3/8 22:50
 */
public class Test06_DeadLock {
    @Test
    public void test() throws InterruptedException {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new InnerClass(lockA,lockB),"A").start();
        new Thread(new InnerClass(lockB,lockA),"B").start();

        while (Thread.activeCount()>2){
            Thread.yield();
        }

    }

    class InnerClass implements Runnable{

        private String lockA;
        private String lockB;

        public InnerClass(String lockA, String lockB) {
            this.lockA = lockA;
            this.lockB = lockB;
        }

        @Override
        public void run() {
            synchronized (lockA){
                System.out.println(Thread.currentThread().getName()+"lock:"+lockA+"---->get "+lockB);

                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (lockB){
                    System.out.println(Thread.currentThread().getName()+"lock:"+lockB+"---->get "+lockA);
                }
            }
        }
    }



}
